<template>
  <div class="exit-application">
    <el-tabs v-model="activeTab" @tab-change="handleTabClick">
      <el-tab-pane label="大学科技园退租" name="scienceParkExit">
        <div class="application-card" v-if="scienceParkExitData.length > 0">
          <el-card v-for="item in scienceParkExitData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>退租信息</span>
                <div class="card-actions">
                  <el-button  type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'scienceParkExit')">打印</el-button>
                  <!-- 状态为0时显示编辑和删除按钮 -->
                  <el-button v-if="item.status === 0" type="primary" link @click="handleEdit(item, 'scienceParkExit')">编辑</el-button>
                  <el-button v-if="item.status === 0" type="danger" link @click="handleDelete(item.id, 'scienceParkExit')">删除</el-button>
                  <!-- 状态为1时显示撤回和删除按钮 -->
                  <el-button v-if="item.status === 1" type="primary" link @click="handleWithdraw(item, 'scienceParkExit')">撤回</el-button>
<!--                  <el-button v-if="item.status === 1" type="danger" link @click="handleDelete(item.id, 'scienceParkExit')">删除</el-button>-->
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.enterpriseName }}</span>
              </div>
              <div class="info-item">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDate(item.applicationDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无退租记录" />
      </el-tab-pane>

      <el-tab-pane label="众创空间退出" name="innovationSpaceExit">
        <div class="application-card" v-if="innovationSpaceExitData.length > 0">
          <el-card v-for="item in innovationSpaceExitData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>退租信息</span>
                <div class="card-actions">
                  <!-- 状态为0时显示编辑和删除按钮 -->
                  <el-button  type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'innovationSpaceExit')">打印</el-button>
                  <el-button v-if="item.status === 0" type="primary" link @click="handleEdit(item, 'innovationSpaceExit')">编辑</el-button>
                  <el-button v-if="item.status === 0" type="danger" link @click="handleDelete(item.id, 'innovationSpaceExit')">删除</el-button>
                  <!-- 状态为1时显示撤回和删除按钮 -->
                  <el-button v-if="item.status === 1" type="primary" link @click="handleWithdraw(item, 'innovationSpaceExit')">撤回</el-button>
<!--                  <el-button v-if="item.status === 1" type="danger" link @click="handleDelete(item.id, 'innovationSpaceExit')">删除</el-button>-->
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业/团队：</span>
                <span class="value">{{ item.enterpriseTeam }}</span>
              </div>
              <div class="info-item">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDate(item.exitTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag type="primary" v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无退租记录" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { getMyexitApplicationForm, getMyexitCreateSpaceForm, delImmigrantApplication, delexitCreateSpaceForm, editexitApplicationForm, editexitCreateSpaceForm } from '@/api/personal-center';
import dayjs from "dayjs";
import type { AjaxResult } from '@/types/resultTypes';

const router = useRouter();
const activeTab = ref('scienceParkExit');

// 列表数据
const scienceParkExitData = ref<any[]>([]);
const innovationSpaceExitData = ref<any[]>([]);

// 获取大学科技园退租列表
const getScienceParkExitList = async () => {
  try {
    const res = await getMyexitApplicationForm() as unknown as AjaxResult<any>;
    if (res.code === 200) {
      scienceParkExitData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    ElMessage.error('获取大学科技园退租列表失败');
  }
};

// 获取众创空间退出列表
const getInnovationSpaceExitList = async () => {
  try {
    const res = await getMyexitCreateSpaceForm() as unknown as AjaxResult<any>;
    if (res.code === 200) {
      innovationSpaceExitData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    console.error('获取众创空间退出列表失败:', error);
  }
};

// 处理标签页切换
const handleTabClick = () => {
  switch (activeTab.value) {
    case 'scienceParkExit':
      getScienceParkExitList();
      break;
    case 'innovationSpaceExit':
      getInnovationSpaceExitList();
      break;
  }
};

// 编辑退租申请
const handleEdit = (row: any, type: string) => {
  switch (type) {
    case 'scienceParkExit':
      router.push(`/personal-center/graduation-or-exit/kjy-exit?id=${row.id}`);
      break;
    case 'innovationSpaceExit':
      router.push(`/personal-center/graduation-or-exit/zhongchuang-exit?id=${row.id}`);
      break;
  }
};

// 撤回操作
const handleWithdraw = async (item: any, type: string) => {
  try {
    await ElMessageBox.confirm('确定要撤回该退租申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    let res;
    const updateData = {
      id: item.id,
      status: 0 // 将状态更新为0（未提交）
    };

    switch (type) {
      case 'scienceParkExit':
        res = await editexitApplicationForm(updateData) as unknown as AjaxResult<any>;
        break;
      case 'innovationSpaceExit':
        res = await editexitCreateSpaceForm(updateData) as unknown as AjaxResult<any>;
        break;
    }

    if (res?.code === 200) {
      ElMessage.success('撤回成功');
      handleTabClick(); // 刷新列表
    } else {
      ElMessage.error(res?.msg || '撤回失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回失败:', error);
      ElMessage.error('撤回失败');
    }
  }
};

// 删除退租申请
const handleDelete = async (id: string | number, type: string) => {
  try {
    await ElMessageBox.confirm('确定要删除该退租申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    let res;
    switch (type) {
      case 'scienceParkExit':

        res = await delImmigrantApplication(id.toString()) as unknown as AjaxResult<any>;
        break;
      case 'innovationSpaceExit':
        res = await delexitCreateSpaceForm(id.toString()) as unknown as AjaxResult<any>;
        break;
    }

    if (res?.code === 200) {
      ElMessage.success('删除成功');
      handleTabClick(); // 刷新列表
    } else {
      ElMessage.error(res?.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除退租申请失败:', error);
      ElMessage.error('删除失败');
    }
  }
};
const handleprint = (id: any, type: string) => {
  switch (type) {
    case 'scienceParkExit':
      const scienceParkRoute = router.resolve({
        name: 'kjyexitprint',
        query: {
          id,
        },
      });
      window.open(scienceParkRoute.href, '_blank'); // 使用 .href 属性
      break;
    case 'innovationSpaceExit':
      const innovationSpaceRoute = router.resolve({
        name: 'zhongchuangexitprint',
        query: {
          id,
        },
      });
      window.open(innovationSpaceRoute.href, '_blank'); // 使用 .href 属性
      break;
  }
};
// 格式化时间
const formatDate = (date: string | number | Date | null | undefined) => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD');
};

// 初始化
onMounted(() => {
  handleTabClick();
});
</script>

<style lang="scss" scoped>
.exit-application {
  width: 100%;
  padding: 20px;

  :deep(.el-tabs__content) {
    padding: 20px 0;
  }

  .application-card {
    max-width: 1000px;
    margin: 0 auto;

    .mb-4 {
      margin-bottom: 16px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-actions {
        display: flex;
        gap: 10px;
      }
    }

    .card-content {
      .info-item {
        margin-bottom: 16px;
        display: flex;
        align-items: center;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 100px;
          color: #606266;
        }

        .value {
          color: #303133;
        }
      }
    }
  }
}
</style>